<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>可拖动排序的表格</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
            cursor: pointer;
        }
        tr.draggable {
            cursor: move;
        }
    </style>
</head>
<body>
    <h1>可拖动排序的表格</h1>
    <table id="myTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            <tr class="draggable">
                <td>Alice</td>
                <td>30</td>
                <td>New York</td>
            </tr>
            <tr class="draggable">
                <td>Bob</td>
                <td>25</td>
                <td>Los Angeles</td>
            </tr>
            <tr class="draggable">
                <td>Charlie</td>
                <td>35</td>
                <td>Chicago</td>
            </tr>
        </tbody>
    </table>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <script>
        $(function() {
            // 初始化拖动排序
            $("#myTable tbody").sortable({
                items: "tr.draggable",
                cursor: "move",
                placeholder: "ui-state-highlight"
            }).disableSelection();

            // 表头点击排序
            $("th").click(function() {
                var index = $(this).index();
                var rows = $("#myTable tbody tr").get();
                rows.sort(function(a, b) {
                    var keyA = $(a).children("td").eq(index).text();
                    var keyB = $(b).children("td").eq(index).text();
                    return keyA.localeCompare(keyB);
                });
                $.each(rows, function(index, row) {
                    $("#myTable").children("tbody").append(row);
                });
            });
        });
    </script>
</body>
</html>